package com.xhj.es.service.impl;

import com.alibaba.fastjson.JSON;
import com.xhj.es.entity.Content;
import com.xhj.es.service.ContentService;
import com.xhj.es.util.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ContentServiceImpl implements ContentService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public List<Map<String, Object>> searchPage(String keyword, Integer pageNo, Integer pageSize) {
        if (pageNo < 0) pageNo = 0;
        SearchRequest searchRequest = new SearchRequest("dd_goods");
        // 构建搜索条件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 精确查询
        TermQueryBuilder termQuery = QueryBuilders.termQuery("name", keyword);
        searchSourceBuilder.query(termQuery);
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        // 设置分页条件
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);
        // 设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        // 关闭多个高亮显示
        highlightBuilder.requireFieldMatch(false);
        searchSourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            List<Map<String,Object>> results = new ArrayList<>();
            for (SearchHit hit : hits.getHits()) {
                // 获取高亮字段集合
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField name = highlightFields.get("name");
                // 获取原来响应集合
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                // 获取高亮的集合
                if (name != null) {
                    Text[] fragments = name.getFragments();
                    // 遍历高亮集合并代替原来的字段
                    String newName = "";
                    for (Text fragment : fragments) {
                        newName += fragment;
                    }
                    sourceAsMap.put("name",newName);
                }
                results.add(sourceAsMap);
            }
            return results;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据关键字获取数据，并构造es索引
     * @param keyword
     * @return
     */
    @Override
    public boolean parseContent(String keyword){
        try {
            BulkRequest bulkRequest = new BulkRequest();
            bulkRequest.timeout("60s");
            // 爬取当当网数据
            List<Content> contents = HtmlParseUtil.ddParse(keyword);
            for (Content content : contents) {
                bulkRequest.add(new IndexRequest("dd_goods")
                        .source(JSON.toJSONString(content), XContentType.JSON));
            }
            BulkResponse responses = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            return !responses.hasFailures();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

}
